package tsinghua.smxq.mc;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class UpdateProfileActivity extends Activity {
	TextView tvBirthday;
	RadioGroup rgGender, rgClass;
	RadioButton rbMale, rbFemale, rbTeacher, rbStudent, rbOthers;
	EditText etMobilephone, etEmail;
	Integer iGender, iClass;
	Button upSubmit, upCancel;
	Timestamp tt = Session.user.getBirthday();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.updateprofile_view);
		rgGender = (RadioGroup) findViewById(R.id.rg_gender);
		rbMale = (RadioButton) findViewById(R.id.rb_male);
		rbFemale = (RadioButton) findViewById(R.id.rb_female);
		rbTeacher = (RadioButton) findViewById(R.id.rb_teacher);
		rbStudent = (RadioButton) findViewById(R.id.rb_student);
		rbOthers = (RadioButton) findViewById(R.id.rb_others);
		rgGender.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				// TODO Auto-generated method stub

				if (arg1 == rbMale.getId()) {
					iGender = 1;
				} else if (arg1 == rbFemale.getId()) {
					iGender = 0;
				}

			}

		});

		if (Session.user.getGender() == 0) {
			rbFemale.setChecked(true);
			iGender = 0;
		} else if (Session.user.getGender() == 1) {
			rbMale.setChecked(true);
			iGender = 1;
		}

		rgClass = (RadioGroup) findViewById(R.id.rg_class);
		rgClass.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				if (checkedId == rbTeacher.getId()) {
					iClass = 0;
				} else if (checkedId == rbStudent.getId()) {
					iClass = 1;
				} else {
					iClass = -1;
				}
			}

		});

		if (Session.user.getUserClass() == 0) {
			rbTeacher.setChecked(true);
			iClass = 0;
		} else if (Session.user.getUserClass() == 1) {
			rbStudent.setChecked(true);
			iClass = 1;
		} else if (Session.user.getUserClass() == -1) {
			rbOthers.setChecked(true);
			iClass = -1;
		}

		etMobilephone = (EditText) findViewById(R.id.et_mobilephone);
		if (Session.user.getMobilePhone() != null
				&& Session.user.getMobilePhone().compareTo("") != 0) {
			etMobilephone.setText(Session.user.getMobilePhone());
		}
		tvBirthday = (TextView) findViewById(R.id.tv_upbirthday);
		if (Session.user.getBirthday() != null) {
			int year = 1900 + Session.user.getBirthday().getYear();
			int month = Session.user.getBirthday().getMonth();
			int day = Session.user.getBirthday().getDate();
			tvBirthday.setText(year + "-"+(month+1)+"-"+day);
		} else {
			tvBirthday.setText("点我编辑");
		}
		tvBirthday.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				DatePickerDialog dialog;
				if (Session.user.getBirthday() != null) {
					int year = 1900 + Session.user.getBirthday().getYear();
					int month = Session.user.getBirthday().getMonth();
					int day = Session.user.getBirthday().getDate();
					dialog = new DatePickerDialog(UpdateProfileActivity.this,
							dateListener, year, month, day);
				} else {
					Calendar calendar = Calendar.getInstance();
					dialog = new DatePickerDialog(UpdateProfileActivity.this,
							dateListener, calendar.get(Calendar.YEAR), calendar
									.get(Calendar.MONTH), calendar
									.get(Calendar.DAY_OF_MONTH));

				}
				dialog.show();

			}

			DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {

				@Override
				public void onDateSet(DatePicker view, int year,
						int monthOfYear, int dayOfMonth) {
					// TODO Auto-generated method stub
					tvBirthday.setText(year + "-" + (monthOfYear + 1) + "-"
							+ dayOfMonth);
					tt = new Timestamp(year-1900, monthOfYear + 1, dayOfMonth, 0, 0,
							0, 0);
				}
			};

		});
		etEmail = (EditText) findViewById(R.id.et_email);
		if (Session.user.getEmail() != null
				&& Session.user.getEmail().compareTo("") != 0) {
			etEmail.setText(Session.user.getEmail());
		}
		upSubmit = (Button) findViewById(R.id.up_submit);
		upSubmit.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HttpClient httpclient = new DefaultHttpClient();
				ArrayList<NameValuePair> qparams = new ArrayList<NameValuePair>();
				qparams.add(new BasicNameValuePair("method", "updateUserInfo"));
				qparams.add(new BasicNameValuePair("id", String
						.valueOf(Session.user.getId())));
				qparams.add(new BasicNameValuePair("password", Session.user
						.getPassword()));
				qparams.add(new BasicNameValuePair("username", Session.user
						.getUserName()));
				qparams.add(new BasicNameValuePair("mobilephone", etMobilephone
						.getText().toString()));
				qparams.add(new BasicNameValuePair("email", etEmail.getText()
						.toString()));
				qparams.add(new BasicNameValuePair("gender", String
						.valueOf(iGender)));
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				if (tt != null) {

					qparams.add(new BasicNameValuePair("birthday", df
							.format(tt)));
				}
				qparams.add(new BasicNameValuePair("vocationid", String
						.valueOf(iClass)));
				try {

					URI uri = URIUtils.createURI("http", Constants.serverIP,
							8080, "MobileCityServer/UserServlet",
							URLEncodedUtils.format(qparams, "UTF-8"), null);
					HttpGet httpget = new HttpGet(uri);
					HttpResponse response = httpclient.execute(httpget);
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						String contentString = EntityUtils.toString(entity);
						JSONObject o = new JSONObject(contentString);
						if (o.getInt("status") == 1) {
							Toast.makeText(UpdateProfileActivity.this, "更新成功",
									Toast.LENGTH_LONG).show();
							Session.user.setBirthday(tt);
							Session.user.setEmail(etEmail.getText().toString());
							Session.user.setMobilePhone(etMobilephone.getText()
									.toString());
							Session.user.setGender(iGender);
							Session.user.setUserClass(iClass);
							UpdateProfileActivity.this
									.startActivity(new Intent(
											UpdateProfileActivity.this,
											MobileCityActivity.class));
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});
		upCancel = (Button) findViewById(R.id.up_cancel);
		upCancel.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				UpdateProfileActivity.this.startActivity(new Intent(
						UpdateProfileActivity.this, MobileCityActivity.class));
			}

		});
	}
}
